<template>
    <l-layout class="l-tab-page" :left="400" >
        <template #left >
            <l-panel style="padding-right:0;" >
                <template #toolLeft >
                    <div style="height:28px;" >
                        <el-form ref="form" :inline="true" :show-message="false" :model="dbFormData" size="mini" >
                            <el-form-item :label="$t('数据表')" prop="f_DbId">
                                <el-select style="width:140px;" v-model="dbFormData.f_DbId" :placeholder="$t('请选择数据库')">
                                    <el-option-group
                                    v-for="group in lr_dblinkTree"
                                    :key="group.id"
                                    :label="group.label">
                                    <el-option
                                        v-for="item in group.children"
                                        :key="item.id"
                                        :label="item.label"
                                        :value="item.id">
                                    </el-option>
                                    </el-option-group>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="f_DbTable" style="margin-right:0;">
                                <el-input  style="width:168px;" :placeholder="$t('请选择表')" readonly="readonly"  v-model="dbFormData.f_DbTable" >
                                    <span slot="append"
                                            @click="handleAddTable">
                                        <el-button slot="append" icon="el-icon-more"></el-button>
                                    </span>
                                </el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                </template>

                <el-tree 
                    ref="columnsTree"
                    show-checkbox
                    node-key="id"
                    :data="tableColumns" 
                    @check="handleColumnCheck"
                    v-loading="columnsLoading"
                    >
                    <span class="lr-tree-node"  slot-scope="{ node }">
                        {{ $t(node.label) }}
                    </span>
                </el-tree>
            </l-panel>
        </template>
        <l-panel style="padding-left:0;" >
            <template #toolLeft >
                <div style="height:28px;" >
                    <el-form ref="form" :inline="true" :show-message="false" :model="formData" :rules="rules" size="mini" >
                        <el-form-item :label="$t('模版名称')" prop="f_Name">
                            <el-input style="width:180px;" :placeholder="$t('请输入')" v-model="formData.f_Name">
                            </el-input>
                        </el-form-item>
                        <el-form-item :label="$t('绑定按钮')" prop="f_ModuleBtnId">
                            <l-select style="width:152px;" :options="btnOptions" :placeholder="$t('请选择')" v-model="formData.f_ModuleBtnId" >
                            </l-select>
                        </el-form-item>
                        <el-form-item style="margin-right:0;" :label="$t('错误机制')" prop="f_ErrorType">
                            <l-select style="width:80px;" :placeholder="$t('请选择')" :options="[{label:'跳过',value:1},{label:'终止',value:0}]" v-model="formData.f_ErrorType">
                            </l-select>
                        </el-form-item>
                    </el-form>
                </div>
            </template>
            <l-table :columns="columns" :dataSource="tableData"  >
                <template v-slot:f_ColName="scope" >
                    <el-input :placeholder="$t('请输入')" v-model="scope.row.f_ColName" size="mini">
                    </el-input>
                </template>
                <template v-slot:f_OnlyOne="scope" >
                    <el-switch
                        :active-value="1"
                        :inactive-value="0"
                        v-model="scope.row.f_OnlyOne"
                        >
                    </el-switch>
                </template>
                <template v-slot:f_RelationType="scope" >
                    {{formatText(scope.row.f_RelationType,scope.row)}}
                </template>
                <vxe-column :resizable="false" :label="$t('操作')" :width="48" >
                    <template slot-scope="scope">
                        <el-button
                            type="text"  
                            size="mini" 
                            @click.stop="handleTableClick(scope.$rowIndex, scope.row)">
                            {{$t('设置')}}
                        </el-button>
                    </template>
                </vxe-column>
            </l-table>
        </l-panel>
        <l-codetable-selectdialog 
            :visible.sync="dbtableSelectdialog"
            :dbCode="dbFormData.f_DbId"
            :isOkClose="false"
            :multiple="false"
            @select="dbSelect"
            >
        </l-codetable-selectdialog>
        <l-dialog
            :title="$t(`设置字段属性`)"
            :visible.sync="formVisible"

            @ok="handleSave"
            @close="handleCloseForm"
            @opened="handleOpenedForm"
            >
            <div class="l-from-body" >
                <el-form :model="formData2" :rules="rules2" size="mini"  ref="form2" label-width="80px" >
                    <el-form-item :label="$t('字段')" prop="f_Name">
                        <el-input readonly v-model="formData2.f_Name"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('关联类型')" prop="f_RelationType">
                        <l-select 
                            :placeholder="$t('请选择')" 
                            :options="relationTypeOptions" 
                            v-model="formData2.f_RelationType"
                            @change="handleRelationChange"
                            >
                        </l-select>
                    </el-form-item>
                    <el-form-item  v-if="formData2.f_RelationType == 2" :label="$t('数据选项')" prop="f_DataItemCode">
                        <l-tree-select
                            :placeholder="$t('请选择')" 
                            :options="lr_dataItemClassifysTree" 
                            v-model="formData2.f_DataItemCode">
                        </l-tree-select>
                    </el-form-item>
                    <el-form-item v-if="formData2.f_RelationType == 3" :label="$t('数据选项')" prop="f_DSourceId">
                        <l-select
                            :placeholder="$t('请选择')" 
                            :options="lr_dataSource" 
                            labelKey="f_Name" 
                            valueKey="f_Code"
                            v-model="formData2.f_DSourceId"
                            @change="handleDataSourceChange"
                            >
                        </l-select>
                    </el-form-item>
                    <el-form-item v-if="formData2.f_RelationType == 3" :label="$t('导入字段')" prop="f_DSourceExcelId">
                        <l-select
                            :placeholder="$t('请选择')" 
                            :options="colNames" 
                            v-model="formData2.f_DSourceExcelId">
                        </l-select>
                    </el-form-item>
                    <el-form-item v-if="formData2.f_RelationType == 3" :label="$t('保存字段')" prop="f_DSourceDBId">
                        <l-select
                            :placeholder="$t('请选择')" 
                            :options="colNames" 
                            v-model="formData2.f_DSourceDBId">
                        </l-select>
                    </el-form-item>
                    <el-form-item v-if="formData2.f_RelationType == 4" :label="$t('固定数值')" prop="f_Value">
                        <el-input v-model="formData2.f_Value"></el-input>
                    </el-form-item>
                    <!-- 单据编码 -->
                    <el-form-item v-if="formData2.f_RelationType == 8" :label="$t('单据编码')" prop="f_EnCode">
                        <l-select
                            :placeholder="$t('请选择')" 
                            :options="codeList" 
                            v-model="formData2.f_EnCode"
                            >
                        </l-select>
                    </el-form-item>
                </el-form>
            </div>
        </l-dialog>
    </l-layout>
</template>
<script>
const apiModule = window.$api.system.module
const apiCodeTable = window.$api.data.codeTable
export default {
    props:{
        moduleId:String,
        moduleCode:String
    },
    data(){
        return {
            dbtableSelectdialog:false,

            btnOptions:[],
            columns:[
                {label:'字段',prop:'f_Name',minWidth:'140'},
                {label:'Excel列名',prop:'f_ColName',minWidth:'140'},
                {label:'唯一性',prop:'f_OnlyOne',width:'64',align:'center'},
                {label:'描述',prop:'f_RelationType',width:'160'},
            ],
            tableData:[],
            dbFormData:{
                f_DbId:'',
                f_DbTable:''
            },
            formData:{
                f_Name:'',
                f_ModuleBtnId:'',
                f_ErrorType:1
            },
            rules:{
                f_Name: [
                    { required: true, message: this.$t('请输入名称') }
                ],
                f_ModuleBtnId: [
                    { required: true, message: this.$t('请选择按钮') }
                ],
                f_ErrorType: [
                    { required: true, message: this.$t('请选择错误机制') }
                ],
            },
            tableMap:{},
            tableColumns:[],
            columnsLoading:false,

            formVisible:false,
            formEditRow:null,
            formEditIndex:0,
            formData2:{
                f_Name:'',
                f_RelationType:0,
                f_DataItemCode:'',
                f_DSourceId:'',
                f_DSourceExcelId:'',
                f_DSourceDBId:'',
                f_Value:'',
                f_EnCode:''//单据编码
            },
            rules2:{
                f_RelationType: [
                    { required: true, message: this.$t('请输选择关联类型') }
                ],
                f_DataItemCode: [
                    { required: true, message: this.$t('请选择数据字典') }
                ],
                f_DSourceId: [
                    { required: true, message: this.$t('请选择数据源') }
                ],
                f_DSourceExcelId: [
                    { required: true, message: this.$t('请选择导入字段') }
                ],
                f_DSourceDBId: [
                    { required: true, message: this.$t('请选择保存字段') }
                ],
                f_Value: [
                    { required: true, message: this.$t('请填写固定数值') }
                ],
                f_EnCode: [
                    { required: true, message: this.$t('请选择单据编码') }
                ],
            },
            relationTypeOptions:[
                { value: 0, label: this.$t("无关联") }, 
                { value: 1, label: this.$t("GUID") }, 
                { value: 2, label: this.$t("数据字典") },
                { value: 3, label: this.$t("数据来源") },
                { value: 4, label: this.$t("固定数据") },
                { value: 5, label: this.$t("登录者ID") },
                { value: 6, label: this.$t("登录者名字") },
                { value: 7, label: this.$t("导入时间") },
                { value: 8, label: this.$t("单据编码") }
            ],
            colNames:[]
        }
    },
    computed:{
        codeList(){
            if(this.lr_codeList){
                const list = this.lr_codeList || []
                return list.map(t=>{
                    return {label:t.f_FullName,value:t.f_EnCode}
                })
            }
            else{
                return []
            }
        }
    },
    created(){
        this.lr_loadCodeList && this.lr_loadCodeList()
    },
    watch:{
        moduleId:{
            handler(val){
                this.LoadButtons(val)
            },
            immediate: true
        }
    },
    mounted () {
        this.initDbLink()
        this.lr_loadDataItemClassifys()
        this.lr_loadDataSourceList()
    },
    methods:{
        async initDbLink(){
            await this.lr_loadDblink(false)
        },
        // 添加数据表
        handleAddTable(){
            if(this.dbFormData.f_DbId){
                this.dbtableSelectdialog = true
            }
            else{
                this.$message({
                    message: this.$t('请选择数据库'),
                    type: 'warning'
                })
            }
        },
        async dbSelect(obj,showLoading, hideLoading){
            showLoading()
            this.dbFormData.f_DbTable = obj[0].f_TableName
            if(!this.tableMap[ this.dbFormData.f_DbTable]){
                const codeTables = await this.$awaitWraper(apiCodeTable.getList(this.dbFormData.f_DbId,this.dbFormData.f_DbTable))
                if(codeTables){
                    this.tableMap[ this.dbFormData.f_DbTable]  = codeTables[0].lr_db_codecolumnsList.map(t=>({
                        label:t.f_Description?`${t.f_DbColumnName}(${t.f_Description})`:t.f_DbColumnName,
                        id:t.f_DbColumnName,
                        name:t.f_DbColumnName,
                        csType:t.f_CsType,
                        isIdentity:t.f_IsIdentity == 1,
                        isPrimary:t.f_IsPrimaryKey == 1,
                        isNullable:t.f_IsNullable == 1,
                        coment:t.f_Description
                    }))
                }
            }
            this.tableColumns = this.tableMap[this.dbFormData.f_DbTable] || []
            this.tableData = this.tableColumns.map(t=>{return {
                f_Name:t.name,
                f_ColName:t.coment ||t.name,
                f_CsType:t.csType,
                f_OnlyOne:0,
                f_RelationType:0,
                f_DataItemCode:'',
                f_DSourceId:'',
                f_DSourceExcelId:'',
                f_DSourceDBId:'',
                f_Value:'',
                f_EnCode:''}})

            this.$refs.columnsTree.setCheckedKeys(this.tableColumns.map(t=>t.name))
            this.dbtableSelectdialog = false
            hideLoading()
        },

        async LoadButtons(val){
            const res = await this.$awaitWraper(apiModule.getButtons(val))
            this.btnOptions = res.filter(t=>![this.$t('新增'),this.$t('编辑'),this.$t('删除'),this.$t('详情'),this.$t('导出')].includes(t.f_FullName)).map(t=>{return {label:t.f_FullName,value:t.f_EnCode}})
        },
        handleColumnCheck(node,data){
            const columnChecked = data.checkedKeys
            if(columnChecked.indexOf(node.name) > -1){
                this.tableData.push({
                    f_Name:node.name,f_ColName:node.coment ||node.name,
                    f_CsType:node.csType,
                    f_OnlyOne:0,
                    f_RelationType:0,
                    f_DataItemCode:'',
                    f_DSourceId:'',
                    f_DSourceExcelId:'',
                    f_DSourceDBId:'',
                    f_Value:'',
                    f_EnCode:''})
            }
            else{
                this.tableData.splice(this.tableData.findIndex(t=>t.f_Name == node.name), 1)
            }
        },
        handleTableClick($index,row){
            this.formVisible = true
            this.formEditRow = row
            this.formEditIndex = $index
        },
        handleSave(){
            this.$refs.form2.validate((valid) => {
                if(valid){
                    this.$set(this.tableData, this.formEditIndex, this.$deepClone(this.formData2))
                    this.formVisible = false
                }
            })
            
        },
        handleCloseForm(){
            this.$refs.form2 && this.$refs.form2.resetFields()
        },
        handleOpenedForm(){
            this.formData2 = this.$deepClone(this.formEditRow)
        },

        handleRelationChange(){
            this.formData2.f_DataItemCode = ''
            this.formData2.f_DSourceId = ''
            this.formData2.f_DSourceExcelId = ''
            this.formData2.f_DSourceDBId = ''
            this.formData2.f_Value = ''
            this.formData2.f_EnCode=''
        },

        async handleDataSourceChange(item){
            if(this.$validatenull(item)){
                this.formData2.f_DSourceExcelId = ''
                this.formData2.f_DSourceDBId = ''
                this.colNames = []
            }
            else{
                await this.lr_loadDataSourceColNames(item.f_Code,false)
                const _data =  this.lr_dataSourceCol[item.f_Code].map(t=>{return {value:t,label:t}})
                this.colNames = _data
                this.formData2.f_DSourceExcelId = _data[0].value
                this.formData2.f_DSourceDBId = _data[0].value
                
            }
        },
        formatText(type,row){
            switch (type) {
                case 0://无关联
                    return this.$t('无关联')
                case 1://GUID
                    return this.$t('系统产生GUID')
                case 2://数据字典
                    return this.$t('关联数据字典')
                case 3://数据表
                    return this.$t('关联数据表')
                case 4://固定值
                    return this.$t('固定数值/') + row.f_Value
                case 5://操作人ID
                    return this.$t('登录者ID')
                case 6://操作人名字
                    return this.$t('登录者名字')
                case 7://操作时间
                    return this.$t('导入时间')
                case 8://单据编码
                    return this.$t('单据编码')
            }
        },

        // 重置表单
        resetForm(){
            this.tableColumns = []
            this.tableData = []
            this.dbFormData.f_DbId =  ''
            this.dbFormData.f_DbTable =  ''
            this.$refs.form && this.$refs.form.resetFields()
        },
        // 校验表单
        validateForm(callback){
            this.$refs.form.validate((valid) => {
                if(valid){
                    if(this.tableData.length == 0){
                        this.$message({
                            type: 'error',
                            message: this.$t('请添加设置字段')
                        })
                    }
                    else{
                        callback()
                    }
                }
            })
        },
        // 设置表单数据
        async setForm(data){

            this.formData = data.entity
            this.dbFormData.f_DbId =  data.entity.f_DbId
            this.dbFormData.f_DbTable =  data.entity.f_DbTable 
            this.tableData = data.list
            this.columnsLoading = true

            const codeTables = await this.$awaitWraper(apiCodeTable.getList(this.dbFormData.f_DbId,this.dbFormData.f_DbTable))
            if(codeTables && codeTables.length >0){
                this.tableMap[ this.dbFormData.f_DbTable]  = codeTables[0].lr_db_codecolumnsList.map(t=>({
                    label:t.f_Description?`${t.f_DbColumnName}(${t.f_Description})`:t.f_DbColumnName,
                    id:t.f_DbColumnName,
                    name:t.f_DbColumnName,
                    csType:t.f_CsType,
                    isIdentity:t.f_IsIdentity == 1,
                    isPrimary:t.f_IsPrimaryKey == 1,
                    isNullable:t.f_IsNullable == 1,
                    coment:t.f_Description
                }))
            }

            this.tableColumns = this.tableMap[this.dbFormData.f_DbTable] || []
            this.$refs.columnsTree.setCheckedKeys(data.list.map(t=>t.f_Name))
            this.columnsLoading = false
        },
        // 获取表单数据
        getForm(){
            const entity = this.$deepClone(this.formData)
            entity.f_ModuleId = this.moduleCode
            entity.f_DbId = this.dbFormData.f_DbId
            entity.f_DbTable = this.dbFormData.f_DbTable
            entity.F_BtnName = this.btnOptions.find(t=>t.value == entity.f_ModuleBtnId).label
            return {entity,list:this.$deepClone(this.tableData)}
        }
    }
}
</script>